﻿using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;

namespace RealtyReview.Business.Helpers
{
    public class Serializer
    {
        public static string ToJson<T>(T data)
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
            using (MemoryStream ms = new MemoryStream())
            {
                serializer.WriteObject(ms, data);
                return Encoding.Default.GetString(ms.ToArray());
            }
        }

        public static T ToObject<T>(string jsonString)
        {
            if (jsonString != null)
            {
                byte[] byteArray = Encoding.ASCII.GetBytes(jsonString);
                using (var outputStream = new MemoryStream(byteArray))
                {
                    var serializer = new DataContractJsonSerializer(typeof (T));
                    return (T) serializer.ReadObject(outputStream);
                }
            }
            return default(T);
        }
    }
}
